<?php

namespace app\api\service;

use app\common\model\Order;
use PDOStatement;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Log;
use think\Model;

class OrderService extends BaseService
{

    public function submit($type, $userId, $amount, $discountAmount)
    {
        $order = new Order();

        $data = [
            'type' => $type,
            'user_id' => $userId,
            'order_no' => Order::generate_order_no($type),
            'amount' => $amount,
            'discount_amount' => $discountAmount,
            'total_amount' => bcsub($amount, $discountAmount, 2),
        ];

        $result = $order->data($data)->save();
        if (empty($result)) {
            $this->setMsg('订单写入失败！');
            Log::write('订单写入失败！' . $result, 'error');
            return false;
        }
        return $order;
    }

    /**
     * 回调修改参数
     * @param $outOrderNo
     * @param $payType
     * @return bool
     */
    public function callBack($orderId, $outOrderNo, $payAmount, $payTime, $payType)
    {
        $order = Order::get($orderId);

        $data = [
            'out_order_no' => $outOrderNo,
            'payed_amount' => $payAmount,
            'payed_time' => $payTime,
            'pay_status' => Order::PAY_STATUS_TRUE,
            'status'     => Order::STATUS_PAID,
            'updatetime' => time()
        ];

        switch ($payType) {
            case Order::PAYMENT_TYPE_CASH:
                $data['payment_type'] = Order::PAYMENT_TYPE_CASH;
                break;
            case Order::PAYMENT_TYPE_WECHAT:
                $data['payment_type'] = Order::PAYMENT_TYPE_WECHAT;
                break;
            case Order::PAYMENT_TYPE_ALIPAY:
                $data['payment_type'] = Order::PAYMENT_TYPE_ALIPAY;
                break;
            case Order::PAYMENT_TYPE_UNIPAY:
                $data['payment_type'] = Order::PAYMENT_TYPE_UNIPAY;
                break;
            default:
                break;
        }


        $order->data($data);
        $result = $order->save();
        if (empty($result)) {
            $this->setMsg('修改订单失败！');
            Log::write('修改订单失败！' . $result, 'error');
            return false;
        }

        return true;
    }

    /**
     * 订单详情
     * @param string $orderNo
     * @return array|bool|PDOStatement|string|Model
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function detail(string $orderNo, $userId)
    {
        $order = Order::with([
            'items',
        ])->Where(['order_no' => $orderNo, 'user_id' => $userId])->find();
        if (empty($order)) {
            $this->setMsg('找不到相关的订单信息');
            return false;
        }
        return $order;
    }
}
